package ink.yuanchu.picachoframework.controller;

import com.alibaba.fastjson.JSONObject;
import ink.yuanchu.picachoframework.dao.PermissionsMapper;
import ink.yuanchu.picachoframework.dao.RoleMapper;
import ink.yuanchu.picachoframework.dao.UserMapper;
import ink.yuanchu.picachoframework.entity.Permissions;
import ink.yuanchu.picachoframework.entity.Role;
import ink.yuanchu.picachoframework.entity.User;
import ink.yuanchu.picachoframework.message.Message;
import ink.yuanchu.picachoframework.message.ResultBody;
import ink.yuanchu.picachoframework.service.RoleAssociatedPermissionsService;
import ink.yuanchu.picachoframework.service.RoleService;
import ink.yuanchu.picachoframework.service.UserService;
import ink.yuanchu.picachoframework.util.JwtTokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ziyuan
 * @since 2021-02-19
 */
@RestController
@RequestMapping("/picachoframework/user")
@Api(value = "用户接口")
public class UserController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleAssociatedPermissionsService roleAssociatedPermissionsService;

    /**
     * 测试接口
     * @return
     */
    @GetMapping("/UserList")
    @ApiOperation(value = "查询全部用户",notes = "test")
    public List<User> userList(){
        return userService.findAll();
    }

    /**
     * 测试接口
     * @return
     */
    @GetMapping("/selectAll")
    @ApiOperation(value = "自定义查询全部用户",notes = "test")
    public List<User> selectAll(){
        return userService.selectAll();
    }


    /**
     * ant design pro 在登录校验或页面刷新后会立即调用这个用户路由权限的接口
     * 这里通过解析token  来获取用户的信息
     * 在这里封装好路由权限后  返回给ant design pro
     * @param httpServletRequest
     * @return
     */
    @GetMapping("/info")
    @ApiOperation(value = "路由信息接口",notes = "返回给ant design pro 的路由权限信息")
    public ResponseEntity<JSONObject> getMessage(HttpServletRequest httpServletRequest){
        try {
            // System.out.println(httpServletRequest.getHeader(JwtTokenUtil.TOKEN_HEADER));
            return ResponseEntity.ok(userPermissions(httpServletRequest));
        }catch (RuntimeException e){
            e.printStackTrace();
            return  Message.errorLogin(HttpStatus.UNAUTHORIZED,Message.ERROR_GET_ROUTER);
        }
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @PostMapping("/addUser")
    @ApiOperation(value = "添加用户",notes = "")
    public ResultBody addUser(@RequestBody User user){
        User byNameToUser = null;
        String username = user.getUsername();
        Integer byName = userService.findByName(username);
        if (user != null && byName < 1){
            int insert = userService.addUser(user);
            if (insert == 1){
                 byNameToUser = userService.findByNameToUser(username);
            }
            return ResultBody.success(byNameToUser);
        }else {
            return ResultBody.error("参数接收错误或用户已存在");
        }
    }

    /**
     * 查询所有用户
     * @return
     */
    @GetMapping("/findAll")
    @ApiOperation(value = "查询所有没有逻辑删除的用户",notes = "返回给json")
    public ResponseEntity getUserAll(){
        List<User> users = userService.findAll();
        List<User> userList = new ArrayList<>();
        for (User user : users) {
            String roleId = user.getRoleId();
            Role role = roleService.selectById(roleId);
            if (role != null) {
                String roleName = role.getRoleName();
                user.setRoleId(roleName);
            }else {
                user.setRoleId("没有设定角色");
            }
            userList.add(user);
        }
        return ResponseEntity.ok(userList);
    }

    /**
     * 根据id做逻辑删除
     * @param req
     * @return
     */
    @PostMapping("/deleteById")
    @ApiOperation(value = "根据id删除,逻辑删除",notes = "成功:{code:200,message:成功,result:影响的行数},失败:code: -1,message: 删除失败,result: null")
    public ResultBody deleteById(@RequestBody Map req){
        String id = req.get("id").toString();
        int i = userService.deleteById(id);
        if (i != 0){
            return ResultBody.success(i);
        }else {
            return ResultBody.error("删除失败");
        }
    }

    /**
     * 根据id更新
     * @param user
     * @return
     */
    @PostMapping("/updateById")
    @ApiOperation(value = "根据id更新，传入一个user对象",notes = "")
    public ResultBody updateById(@RequestBody User user){
        if (user != null && user.getId() != null){
            Integer integer = userService.updateByUserId(user);
            return ResultBody.success(integer);
        }else {
            return ResultBody.error("id为空或参数传入错误");
        }
    }




    /**
     * 封装用户权限
     * @param httpServletRequest
     * @return
     */
    private JSONObject userPermissions(HttpServletRequest httpServletRequest){
        //取出token
        String token = httpServletRequest.getHeader(JwtTokenUtil.TOKEN_HEADER);
        //去掉前缀 获取Token字符串  解析出username
        String username = JwtTokenUtil.getUsername(token.replace(JwtTokenUtil.TOKEN_PREFIX, ""));
        //根据username查询用户
        User user = userService.findByNameToUser(username);
        String roleId = user.getRoleId();
        JSONObject jsonObject = new JSONObject();
        Map role = new HashMap();
        role.put("role",roleContent(roleId));
        jsonObject.put("result",role);

        return jsonObject;
    }

    /**
     * 根据角色封装路由
     * @param roleId
     * @return
     */
    private Map roleContent(String roleId){

        Map map = new HashMap();
        List permissionList = new ArrayList();
        List permissions = new ArrayList();

        List<Permissions> permissionsList = roleAssociatedPermissionsService.findAllPermissionsByRoleId(roleId);
        for (Permissions pms:
                permissionsList) {
            Map map1 = new HashMap();
            map1.put("permissionId",pms.getPermissionId());
            map1.put("roleId",roleId);
            map1.put("permissionName",pms.getPermissionName());
            permissions.add(map1);
            permissionList.add(pms.getPermissionId());
        }

        map.put("permissions",permissions);
        map.put("permissionList",permissionList);

        return map;
    }

}

